package com.century.sjt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.entity.Address;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.widget.togglebutton.ToggleButton;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 炳基 on 2016/5/25.
 * 添加地址
 */
public class AddressAddActivity extends BaseActivity{
    private SjtTitleBar titleBar;
    private EditText edName;
    private EditText edPhome;
    private EditText edCountry;
    private EditText edAddress;
    private Button btnSubmit;
    private CheckBox checkBox;
    private String Type;
    private Address address;
    private String isDefault;
    private LinearLayout layout_check;
    private ToggleButton toggleButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout. activity_address_add);
        Intent intent = getIntent();

        if (intent.getStringExtra("Type")==null||"".equals(intent.getStringExtra("Type"))){
            Type="0";
        }else {
            Type=intent.getStringExtra("Type");
            address=(Address) intent.getSerializableExtra("address");
        }
        initView();
        initEvent();
    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        edName =(EditText) findViewById(R.id.et_name);
        edAddress =(EditText) findViewById(R.id.et_address);
//        edCountry =(EditText) findViewById(R.id.et_country);
        edPhome =(EditText) findViewById(R.id.et_phome);
        btnSubmit =(Button) findViewById(R.id.btn_submit);
        checkBox = (CheckBox) findViewById(R.id.add_check);
        layout_check = (LinearLayout) findViewById(R.id.address_add_check);
        toggleButton = (ToggleButton) findViewById(R.id.address_setmr);
    }

    @Override
    protected void initEvent() {
        //       标题栏
//        layout_check.setVisibility(View.GONE);
        titleBar.setTitle(getResources().getString(R.string.tab_address_add));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        checkBox.setVisibility(View.GONE);
        if ("3".equals(Type)||"4".equals(Type)){
//            checkBox.setChecked(true);
            toggleButton.setToggleOn();
            isDefault="1";
        }else {
//            checkBox.setChecked(false);
            toggleButton.setToggleOff();
            isDefault = "0";
        }
//        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    isDefault="1";
//                    toggleButton.setToggleOn();
//                } else {
//                    isDefault="0";
//                    toggleButton.setToggleOff();
//                }
//            }
//        });
        toggleButton.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
//                checkBox.setChecked(on);
                if (on) {
                    isDefault="1";
//                    toggleButton.setToggleOn();
                } else {
                    isDefault="0";
//                    toggleButton.setToggleOff();
                }
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ("".equals(edName.getText().toString())||edName.getText().toString()==null){
                    TipUtil.showToast(getResources().getString(R.string.error_no_receipt_name), AddressAddActivity.this, 1);
                }else if ("".equals(edPhome.getText().toString())||edPhome.getText().toString()==null){
                    TipUtil.showToast(getResources().getString(R.string.error_no_phone), AddressAddActivity.this, 1);
                }
//                else if ("".equals(edCountry.getText().toString())||edCountry.getText().toString()==null){
//                    TipUtil.showToast("请输入国家", AddressAddActivity.this, 1);
//                }
                else if ("".equals(edAddress.getText().toString())||edAddress.getText().toString()==null){
                    TipUtil.showToast(getResources().getString(R.string.error_no_address), AddressAddActivity.this, 1);
                }else {
                    if ("1".equals(Type)) {
                        updataAddress();
                    }else {
                        setAdd();
                    }

                }

            }
        });
        if ("1".equals(Type)){
            edAddress.setText(address.getAddress());
            edPhome.setText(address.getPhone());
//            edCountry.setText(address.getArexz());
            edName.setText(address.getConsignee());
            if ("1".equals(address.getIsDefault())){
//                checkBox.setChecked(true);
                toggleButton.setToggleOn();
            }
            titleBar.setTitle(getResources().getString(R.string.tab_addres_update));
        }

    }

    @Override
    protected void initData() {

    }

    private void setAdd(){
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), AddressAddActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.addAddress, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取地址", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        if ("4".equals(Type)){
                            finish();
                        }else {
                            TipUtil.showToast(getResources().getString(R.string.text_add_success), AddressAddActivity.this, 1);
//                            Intent intent = new Intent();
//                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            intent.setClass(AddressAddActivity.this, AddressManageActivity.class);
//                            startActivity(intent);
                            finish();
                        }

                    } else {//失败
                        TipUtil.showToast(message, AddressAddActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), AddressAddActivity.this, 1);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), AddressAddActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("address",edAddress.getText().toString().trim());
//                map.put("areaName",edCountry.getText().toString().trim());
                map.put("consignee",edName.getText().toString().trim());
                map.put("isDefault",isDefault);
                map.put("phone",edPhome.getText().toString().trim());
//                map.put("zipCode","11111");
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    private void updataAddress(){
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), AddressAddActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.updataAddress, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取地址", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功

                        TipUtil.showToast(getResources().getString(R.string.text_update_success), AddressAddActivity.this, 1);
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setClass(AddressAddActivity.this, AddressManageActivity.class);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, AddressAddActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), AddressAddActivity.this, 1);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), AddressAddActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("sysId",address.getSysId());
                map.put("address",edAddress.getText().toString().trim());
//                map.put("areaName",edCountry.getText().toString().trim());
                map.put("consignee",edName.getText().toString().trim());
                map.put("isDefault",isDefault);
                map.put("phone",edPhome.getText().toString().trim());
//                map.put("zipCode","");
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

}
